package database

import (
	"cld-quick-cli/config"
	"fmt"

	_ "github.com/go-sql-driver/mysql"
	"github.com/jmoiron/sqlx"
)

func InitSqlxDB() (*sqlx.DB, error) {
	if config.Config.MysqlConfig == nil {
		panic("[MysqlConfig] Unavailable configuration")
	}
	dbUser := config.Config.MysqlConfig.Username
	dbPassword := config.Config.MysqlConfig.Password
	dbName := config.Config.MysqlConfig.DbName
	dbURL := config.Config.MysqlConfig.Host
	dbPort := config.Config.MysqlConfig.Port
	sqlDSN := fmt.Sprintf("%s:%s@tcp(%s:%v)/%s?charset=utf8&parseTime=True&loc=Local", dbUser, dbPassword, dbURL, dbPort, dbName)
	db, err := sqlx.Connect("mysql", sqlDSN)
	if err != nil {
		return nil, err
	}
	db.SetMaxOpenConns(config.Config.MysqlConfig.MaxOpenConnes)
	db.SetMaxIdleConns(config.Config.MysqlConfig.MaxIdleConnes)
	return db, nil
}
